import { Controller, Inject, Post, Body } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { JwtPassportMiddleware } from '../middleware/jwt.middleware';
import { execSync } from 'child_process';
import { HttpStatus, MidwayHttpError } from '@midwayjs/core';

// 该控制器主要用于处理状态相关业务
@Controller('/rce')
export class RceController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Post('/ping', { middleware: [JwtPassportMiddleware] })
  async ping(@Body('ip') ip: string) {
    try {
      execSync('cmd /c chcp 65001>nul'); // 设置控制台utf8编码
      const stdout = execSync(`ping ${ip}`, {
        encoding: 'utf-8',
      }).toString();
      return { stdout };
    } catch (err) {
      throw new MidwayHttpError(err.message, HttpStatus.BAD_REQUEST);
    }
  }

  @Post('/exec', { middleware: [JwtPassportMiddleware] })
  async exec(@Body('command') command: string) {
    try {
      eval(`${command}`);
    } catch (err) {
      throw new MidwayHttpError(err.message, HttpStatus.BAD_REQUEST);
    }
    return {};
  }
}
